<template>
<div class="year-month">
  <q-input
    class="select"
    outlined dense
    mask="####-##"
    v-model="time"
  >
    <template v-slot:before>
      <span class="form-name">{{label}}：</span>
    </template>
    <template v-slot:append>
      <q-icon name="iconfont icontubiao-94" size="xs">
      </q-icon>
    </template>
    <q-popup-proxy ref="qDateProxy">
      <q-card class="year-month-detail" style="width:216px">
        <q-card-section class="detail-head">
          <q-icon @click="prevYear()" name="keyboard_arrow_left" size="sm"/>
          <span>{{year}}</span>
          <q-icon @click="nextYear()" name="keyboard_arrow_right" size="sm"/>
        </q-card-section>
        <q-card-section class="month-list">
              <span v-for="(monthItem, monthIndex) in months" :key="monthIndex"
                    :class="{'month-active':monthItem===months[month-1]}" @click="changeMonth(monthIndex)">
                {{monthItem}}</span>
        </q-card-section>
      </q-card>
      <q-separator dark />
    </q-popup-proxy>
  </q-input>
</div>
</template>

<script>
import { date } from 'quasar'
export default {
  name: 'year-month',
  props: {
    label: {
      type: String,
      default: '年月'
    },
    date: {
      type: Date,
      default: new Date()
    }
  },
  data () {
    return {
      time: null,
      year: null,
      month: null,
      months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    }
  },
  created () {
    let time = date.formatDate(this.date.getTime(), 'YYYY-MM-DD HH:mm:ss')
    const timeArr = time.split('-')
    this.year = timeArr[0]
    this.month = timeArr[1]
    this.time = this.year + '-' + this.month
  },
  methods: {
    prevYear () {
      this.year = Number(this.year) - 1
      this.time = this.year + '-' + this.month
    },
    nextYear () {
      this.year = Number(this.year) + 1
      this.time = this.year + '-' + this.month
    },
    changeMonth (index) {
      this.month = index + 1 < 10 ? '0' + (index + 1) : index + 1
      this.time = this.year + '-' + this.month
      this.$emit('changeDate', new Date(this.year, this.month - 1))
      this.$refs.qDateProxy.hide()
    }
  }
}
</script>

<style scoped lang="stylus">
.year-month-detail{
  .detail-head{
    display flex
    align-items center
    justify-content center
    span{
      margin 0 10px
      font-size 16px
    }
  }
  .month-list{
    display flex
    flex-wrap wrap
    align-items center
    &>span{
      flex 40px 0
      line-height 28px
      margin 10px 10px
      border-radius 3px
      text-align center
      transition: background-color 0.3s cubic-bezier(0.25, 0.8, 0.5, 1)
      &:hover{
        background-color rgba(0, 0, 0, .15)
      }
      &.month-active{
        background-color: #cfd6fe !important;
        color: #5f77fd;
        cursor default
      }
    }
  }
}
</style>
